<template>
  <div class="content">
    <el-button type="primary" class="primaryButton" @click="addFunc()" plain>
      <i class="el-icon-plus"></i>
      添加用户
    </el-button>
    <el-table :data="userLists" stripe style="width: 100%;">
      <!--<el-table-column prop="logo" width="80">-->
      <!--<template slot-scope="scope">-->
      <!--<img :src="scope.row.logo" min-width="40" height="40">-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column prop="loginName" label="登录账户"></el-table-column>
      <!--<el-table-column prop="roleNames" label="角色"></el-table-column>-->
      <el-table-column prop="name" label="用户姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号码"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="position" label="职位"></el-table-column>
      <el-table-column prop label="操作">
        <template slot-scope="scope">
          <a class="reset" style="cursor: pointer;" @click="updateFunc(scope.$index, scope.row)">修改</a>
          <i class="line"></i>
          <a
            class="delete"
            style="cursor: pointer;"
            @click.stop="deleteFunc(scope.$index, scope.row.code)"
          >删除</a>
        </template>
      </el-table-column>
    </el-table>
    <div class="block-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog :title="addOrUpdateName" :visible.sync="centerDialogVisible" width="50%" center>
      <div class="dialogContent">
        <el-row style="width: 100%;">
          <el-col :span="12">
            <el-form :rules="rules" ref="form" :model="form" label-width="80px">
              <!--<el-form-item label="用户头像">-->
              <!--<el-upload-->
              <!--class="avatar-uploader"-->
              <!--action="https://jsonplaceholder.typicode.com/posts/"-->
              <!--:show-file-list="false"-->
              <!--:on-success="handleAvatarSuccess"-->
              <!--:before-upload="beforeAvatarUpload">-->
              <!--<img v-if="imageUrl" :src="imageUrl" class="avatar">-->
              <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
              <!--</el-upload>-->
              <!--</el-form-item>-->
              <el-form-item label="登录名" prop="loginName">
                <el-input v-model="form.loginName" :disabled="edit"></el-input>
              </el-form-item>
              <el-form-item label="用户姓名" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="form.phone"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email"></el-input>
              </el-form-item>
              <el-form-item v-if="addOrUpdate == 1" label="登录密码" prop="password">
                <el-input v-model="form.password"></el-input>
              </el-form-item>
              <el-form-item v-if="addOrUpdate == 1" label="确认密码" prop="confirmPassword">
                <el-input v-model="form.confirmPassword"></el-input>
              </el-form-item>
              <el-form-item label="职位" prop="position">
                <el-input v-model="form.position"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" v-show="addOrUpdate == 1" @click="addSave('form')">提交</el-button>
                <el-button type="primary" v-show="addOrUpdate == 2" @click="updateSave('form')">提交</el-button>
                <el-button @click="cancel('form')">关闭</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="24" style="padding: 20px;">
                <el-card :body-style="{ }">
                  <div slot="header">
                    <span>角色列表</span>
                  </div>
                  <!-- card body -->
                  <el-tree
                    :data="roleTreeData"
                    show-checkbox
                    node-key="id"
                    ref="roletree"
                    :default-expanded-keys="[]"
                    :default-checked-keys="roletreechecked"
                    :props="defaultProps"
                  ></el-tree>
                </el-card>
              </el-col>
            </el-row>
            <!--<el-row>-->
              <!--<el-col :span="24" style="padding: 20px;">-->
                <!--<el-card :body-style="{ }">-->
                  <!--<div slot="header">-->
                    <!--<span>部门列表</span>-->
                  <!--</div>-->
                  <!--<el-tree-->
                    <!--:data="departmentTreeData"-->
                    <!--show-checkbox-->
                    <!--node-key="id"-->
                    <!--ref="departmenttree"-->
                    <!--:default-expanded-keys="[]"-->
                    <!--:default-checked-keys="departmentTreechecked"-->
                    <!--:props="defaultProps"-->
                  <!--&gt;</el-tree>-->
                <!--</el-card>-->
              <!--</el-col>-->
            <!--</el-row>-->
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import userService from "services/departmentService";

  export default {
    name: "user",
    data() {
      var checkPhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
        } else {
          const reg = /^[0-9]*$/
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error('请输入正确的手机号'));
          }
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请正确填写邮箱'));
        } else {
          if (value !== '') {
            var reg = /^[A-Za-z0-9]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (!reg.test(value)) {
              callback(new Error('请输入有效的邮箱'));
            }
          }
          callback();
        }
      };
      return {
        addOrUpdate:1,
        addOrUpdateName:'',
        imageUrl: '',
        pageNo: 1,
        pageSize:10,
        userLists: [],
        total: 0,
        edit:false,
        centerDialogVisible: false,
        form: {
          loginName: "",
          name: "",
          phone: "",
          email: "",
          position: "",
          password: "",
          confirmPassword: ""
        },
        treeData: [],
        roleTreeData: [],
        roletreechecked: [],
        departmentTreeData: [],
        departmentTreechecked: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        user: {},
        rules: {
          loginName: [
            {required: true, message: '请输入登录名', trigger: 'blur'},
            {min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'},
            {min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入电话', trigger: 'blur'},
            {min: 3, max: 11, message: '长度在 3 到 11 个数字', trigger: 'blur'},
            {validator: checkPhone, trigger: 'blur'},
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: validateEmail, trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 5, max: 12, message: '长度在 5 到 12个字符'},
            {pattern: /^(\w){5,12}$/, message: '只能输入5-12个字母、数字、下划线'}
          ],
          confirmPassword: [
            {required: true, message: '确认密码', trigger: 'blur'}, {
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('请再次输入密码'))
                } else if (value !== this.form.password) {
                  callback(new Error('两次输入密码不一致'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }]
        }
      };
    },
    mounted() {
      this.userListInitial();
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      userListInitial() {
        let userDate = {index: this.pageNo, size: this.pageSize};
        userService.userList(userDate).then(res => {
          if (res.code == 1) {
            this.userLists = res.list;
            this.total = res.total;
          }
        });
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.userListInitial();
      },
      handleCurrentChange(val) {
        this.pageNo = val;
        this.userListInitial();
      },
      addFunc() {
        this.addOrUpdate = 1
        this.addOrUpdateName = '添加用户'
        this.centerDialogVisible = true;
        this.edit = false
        this.$nextTick(()=>{
          this.$refs.form.resetFields();
          this.form = {
            loginName: '',
            name: '',
            phone: '',
            email: '',
            position: '',
            password: '',
            confirmPassword: ''
          }
        });
        let userAddData = {type: 4, companyCode: ""};
        userService.userAddRoleTree(userAddData).then(res => {
          if (res.code == 1) {
            let _this = this
            _this.roleTreeData = [];
            _this.roletreechecked = [];
            function child(data) {
              if(data.state != undefined){
                _this.roletreechecked.push(data.id);
              }
              data.children.map(value => {
                value.label = value.text
                child(value);
              });
              data.label = data.text
            }
            res.list.map(item => {
              child(item)
              _this.roleTreeData.push(item);
            });
          }
        });
        let userAddDeptData = {type: 4, companyCode: ""};
        userService.userAddDeptTree(userAddDeptData).then(res => {
          if (res.code == 1) {
            let _this = this
            _this.departmentTreeData = [];
            _this.departmentTreechecked = [];
            function child(data) {
              if(data.state != undefined){
                _this.departmentTreechecked.push(data.id);
              }
              data.children.map(value => {
                value.label = value.text
                child(value);
              });
              data.label = data.text
            }
            res.list.map(item => {
              child(item)
              _this.departmentTreeData.push(item);
            });

          }
        });
      },
      addSave(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            let params = this.user
            params.logo = ''
            params.loginName= this.form.loginName
            params.loginPassword= this.form.password
            params.loginPasswordRe= this.form.confirmPassword
            params.name= this.form.name
            params.phone= this.form.phone
            params.email= this.form.email
            params.position=this.form.position
            params.defaultLanguage = 'cn'
            params.userType = 'oem'
            params.roleCode = this.$refs.roletree.getCheckedKeys().join(",")
            params.deptCode = this.$refs.departmenttree.getCheckedKeys().join(",")
//                      delete params.language
            userService.userAddSave(params).then(res => {
              if(res.code == 1){
                this.userListInitial()
                this.$message.success("添加用户信息成功")
              }else{
                this.$message.error("添加用户信息失败")
              }
            })
            this.centerDialogVisible = false;
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      updateFunc(index, model) {
        this.addOrUpdate = 2
        this.edit = true
        this.addOrUpdateName = '修改用户'
        this.user = model
        this.centerDialogVisible = true;
        this.form = model;
        let userDeleteCode = {code: model.code, companyCode: model.companyCode};
        //获取用户角色列表
        userService.userUpdateRoleTree(userDeleteCode).then(res => {
          if (res.code == 1) {
            let _this = this
            _this.roleTreeData = [];
            _this.roletreechecked = [];
            function child(data) {
              if(data.state != undefined){
                _this.roletreechecked.push(data.id);
              }
              data.children.map(value => {
                value.label = value.text
                child(value);
              });
              data.label = data.text
            }
            res.list.map(item => {
              child(item)
              _this.roleTreeData.push(item);
            });
          }
        });
        //获取用户部门列表
        userService.selectDeptUserList(userDeleteCode).then(res => {
          if (res.code == 1) {
            let _this = this
            _this.departmentTreeData = [];
            _this.departmentTreechecked = [];
            function child(data) {
              if(data.state != undefined){
                _this.departmentTreechecked.push(data.id);
              }
              data.children.map(value => {
                value.label = value.text
                child(value);
              });
              data.label = data.text
            }
            res.list.map(item => {
              child(item)
              _this.departmentTreeData.push(item);
            });
          }
        });
      },
      updateSave(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            let params = this.user
            params.imageUpdate = ''
            params.logo = ''
            params.roleCode = this.$refs.roletree.getCheckedKeys().join(",")
            params.deptCode = this.$refs.departmenttree.getCheckedKeys().join(",")
            delete params.language
            userService.userUpdateSave(params).then(res => {
              if(res.code == 1){
                this.$message.success("更新用户信息成功！")
                this.userListInitial()
              }else{
                this.$message.success("更新用户信息失败！")
              }
            })
            this.centerDialogVisible = false;
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      deleteFunc(index, model) {
        let userDeleteCode = {code: model};
        this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
          .then(() => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            userService.userDelete(userDeleteCode).then(res => {
              if (res.code == 1) {
                this.userListInitial();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      cancel(form){
        this.userListInitial()
        this.$refs[form].resetFields();
        this.centerDialogVisible = false;
      },
    }
  };
</script>

<style scoped>
  .content {
    background-color: #ffffff;
    padding:10px 20px;
  }

  .primaryButton {
    margin-right: 50px;
  }

  .block-page {
    text-align: center;
  }

  .reset {
    color: #1890ff;
  }

  .delete {
    color: #f5222d;
  }

  .line {
    display: inline-block;
    width: 1px;
    background: rgba(0, 0, 0, 0.09);
    margin: 0 11px;
    height: 14px;
  }

  .dialogContent {
    display: flex;
    flex-direction: row;
  }

  .el-tree {
    margin-left: 50px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>
